import { Dialog } from 'vant';
import store from '@/store/index';
import router from '@/router/router.js';
export function requestIdleCallback(cb) {
	if ('requestIdleCallback' in window) {
		window.requestIdleCallback(cb);
	} else {
		setTimeout(function() {
			var start = Date.now();
			cb({
				didTimeout: false,
				timeRemaining: function() {
					return Math.max(0, 50 - (Date.now() - start));
				},
			});
		}, 1);
	}
}

export function getCookie(name) {
	var reg = new RegExp(name + '=([^;]*)'),
		arr = document.cookie.match(reg);
	return arr && arr[1];
}
export function setCookie(cname, cvalue, exdays) {
	let d = new Date();
	d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
	let expires = 'expires=' + d.toUTCString();
	document.cookie = cname + '=' + cvalue + '; ' + expires + '; path=/;';
}
export function delCookie(key) {
	let exp = new Date(0);
	document.cookie = key + '=;expires=' + exp.toUTCString() + ';path=/';
}
export function urlKey() {
	var search = {};
	location.search.replace(/([^=&?]*)=([^&]*)/g, function(str, key, value) {
		search[key] = decodeURIComponent(value)
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;');
	});
	return search;
}

export const ToolMixin = {
	methods: {
		formatDate(timer) {
			var time = parseInt(timer) * 1000; // 转换为数字乘以1000
			var date = new Date(time);
			var Y = date.getFullYear() + '-';
			var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
			var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
			let strDate = Y + M + D;
			return strDate;
		},
	},
};

//裁剪段落
export function sliceText(str, num) {
	if (str.length > num) {
		return str.slice(0, num) + '...';
	} else {
		return str;
	}
}

// 格式化标签
export function formatTag(tags) {
	let arr = [];
	tags.map((item, index) => {
		if (item.name.indexOf('折优惠') == -1 && item.name.indexOf('叉叉') == -1) {
			arr.push(item);
		}
	});
	return arr.slice(0, 3);
}

// 强制保留2位小数，不足补 0
export function toDecimal(x) {
	var f = parseFloat(x);
	if (isNaN(f)) {
		return false;
	}
	var f = Math.round(x * 100) / 100;
	var s = f.toString();
	var rs = s.indexOf('.');
	if (rs < 0) {
		rs = s.length;
		s += '.';
	}
	while (s.length <= rs + 2) {
		s += '0';
	}
	return s;
}

export function countdown(val) {
	// 相差的毫秒数
	var msec = val;
	// 计算时分秒数
	let hr = parseInt((msec / 60 / 60) % 24);
	let min = parseInt((msec / 60) % 60);
	let sec = parseInt(msec % 60);
	// 个位数前补零
	hr = hr > 9 ? hr : '0' + hr;
	min = min > 9 ? min : '0' + min;
	sec = sec > 9 ? sec : '0' + sec;
	// 控制台打印
	console.log(`${hr}小时 ${min}分钟 ${sec}秒`);
	// 一秒后递归
	setTimeout(function() {
		countdown();
	}, 1000);
}

// 去除字符串中的横杠
export function removeLine(val) {
	return val.replace(/-/g, '');
}

// 取两个数组的交集
export function intersectionArrs(arr1, arr2) {
	// 分别对两个数组进行单独去重
	const set1 = new Set(arr1);
	const set2 = new Set(arr2);
	// 用小的数组优化遍历速度
	if (set1.size > set2.size) {
		return intersectionArrs(set2, set1);
	}
	const buffer = new Set();
	for (const num of set1) {
		if (set2.has(num)) {
			buffer.add(num);
		}
	}
	return [...buffer];
}

// 格式时间截
export function formatTime(value) {
	let dataTime = '';
	let data = new Date();
	let year = data.getFullYear();
	let month = data.getMonth() + 1 < 10 ? '0' + (data.getMonth() + 1) : data.getMonth() + 1;
	let day = data.getDate() < 10 ? '0' + data.getDate() : data.getDate();
	let h = data.getHours() < 10 ? '0' + data.getHours() : data.getHours();
	let m = data.getMinutes() < 10 ? '0' + data.getMinutes() : data.getMinutes();
	dataTime = year + '年' + month + '月' + day + '日' + h + ':' + m;
	return dataTime;
}

// 防抖
let timeout = null;
export function Debounce(func, wait = 700, immediate = true) {
	if (timeout !== null) clearTimeout(timeout);
	// 立即执行
	if (immediate) {
		var callNow = !timeout;
		timeout = setTimeout(function() {
			timeout = null;
		}, wait);
		if (callNow) typeof func === 'function' && func();
	} else {
		// 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
		timeout = setTimeout(function() {
			typeof func === 'function' && func();
		}, wait);
	}
}

//节流
let pre = new Date();
export function Trol(fn, delay) {
	let now = new Date();
	if (now - pre >= delay) {
		fn();
		pre = new Date();
	}
}

//检查登陆
export function checkLogin() {
	if (!store.state.user.isLogin) {
		Dialog.alert({
			title: '提示',
			message: '您还没登陆',
			confirmButtonText: '马上登陆',
		}).then(() => {
			router.push('/login');
		});
		return false;
	} else return true;
}
